package com.hong;


import com.hong.entity.UserEntity;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.List;

public class ClassPathXmlApplicaionContext {

    private static String PATH;
    private static String ID;
    private static String CLASS;
    private static String NAME;
    private static String VALUE;
    public void init(){
        ID="id";
        CLASS="class";
        NAME="name";
        VALUE="value";
    }

    public ClassPathXmlApplicaionContext(String path) {
        init();
//      获取spring文字名称
        this.PATH = path;
    }

    public Object getBean(String beanId) throws DocumentException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
//        1.解板xml
        if(StringUtils.isEmpty(beanId)){
            return null;
        }
        SAXReader saxReader = new SAXReader();
        Document read = saxReader.read(this.getClass().getClassLoader().getResource(PATH));
        Element rootElement = read.getRootElement();
        List<Element> elements = rootElement.elements();
        for (Element element:elements){
            String id = element.attributeValue(ID);
            if(!beanId.equals(id)){
                //结束本次循环
                continue;
            }
//           2.使用beanid查找对应xml节点，获取class节点属性
            //从配置文件中获取bean
            String attClass = element.attributeValue(CLASS);
//           3.使用java的反射机制初始化类
            Class<?> forName = Class.forName(attClass);
            Object newInstance = forName.newInstance();
//           4.获取属性
            List<Element> sonEle = element.elements();
            for (Element el:sonEle){
                String attField = el.attributeValue(NAME);
                String attFieldValue = el.attributeValue(VALUE);
                Field declaredField = forName.getDeclaredField(attField);
                declaredField.setAccessible(true);
                declaredField.set(newInstance, attFieldValue);
            }
            return newInstance;
        }
        return null;
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, InstantiationException, DocumentException, IllegalAccessException {
        ClassPathXmlApplicaionContext app = new ClassPathXmlApplicaionContext("applicationContext.xml");
        UserEntity user1 = (UserEntity) app.getBean("user1");
        System.out.println(user1.toString());

    }
}
